package LeetCode.month01.day10;

import java.util.Deque;
import java.util.LinkedList;

public class No394 {
    public static void main(String[] args) {
        System.out.println(decodeString("100[leetcode]"));
    }

    public static String decodeString(String s) {
        Deque<Character> deque = new LinkedList<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if(c == ']'){
                StringBuilder sb = new StringBuilder();
                while(deque.getLast()!='[') {
                    char c1 = deque.removeLast();
                    sb.append(c1);
                }
                deque.removeLast();
                StringBuilder sb2 = new StringBuilder();
                while(deque.size()!=0&&Character.isDigit(deque.getLast())){
                    sb2.append(deque.removeLast());
                }
                int num = Integer.parseInt(sb2.reverse().toString());
                String s1 = sb.reverse().toString().repeat(num);
                for (int j = 0; j < s1.length(); j++) {
                    deque.add(s1.charAt(j));
                }
            }else deque.add(c);
        }
        StringBuilder result = new StringBuilder();
        int len = deque.size();
        for (int i = 0; i < len; i++) {
            result.append(deque.removeFirst());
        }
        return result.toString();
    }
}
